#include "mysqlManager.h"

using namespace std;

SqlManager::SqlManager()/* : sqlConn(mysql_init(NULL))*/
{
    // connectMysql();
}

SqlManager::~SqlManager()
{    
    // mysql_close(sqlConn);
}

void SqlManager::connectMysql()
{
    // mysql_real_connect(sqlConn, "127.0.0.1", "li", "123456", "tallyBook", 0, NULL, CLIENT_MULTI_STATEMENTS);
}

SqlManager* SqlManager::self = nullptr;
mutex SqlManager::selfMutex;
SqlManager* SqlManager::getInstance()
{
    if(self == nullptr) {
        selfMutex.lock();
        if(self == nullptr) {
            self = new SqlManager();
        }
        selfMutex.unlock();
    }

    return self;
}

bool SqlManager::isUserExist(const std::string &user)
{    
    MYSQL *sqlConn = mysql_init(NULL);
    // 连接数据库时需要判断是否连接成功，
    mysql_real_connect(sqlConn, "127.0.0.1", "li", "123456", "tallyBook", 0, NULL, CLIENT_MULTI_STATEMENTS);
    string sql = "select * from user where name = " + user + ";";
    auto search_res = mysql_query(sqlConn, sql.c_str());
    auto result = mysql_store_result(sqlConn);
    if(result == nullptr) {
        cout << "查询异常\n";
        return false;
    }
    int col = mysql_num_fields(result);//获取列数
    int row = mysql_num_rows(result);//获取行数
    mysql_close(sqlConn);
    return row > 0 ? true : false;
}